<?php

namespace app\controller;


use app\BaseController;
use app\dto\PageDto;
use app\dto\UserDto;
use app\model\AppFun;
use app\model\User;
use app\model\BaseQuery;
use app\proxy\MyRequest;
use app\Request;
use app\service\RedisService;
use app\utils\Md5;
use app\utils\Utils;
use think\facade\Db;
use think\facade\Log;

function toUserDto(UserDto $data)
{
    return $data;
}

class UserController extends BaseController
{


    function getuserinfobyauth(Request $request)
    {
        return Utils::ok($request->getUserInfo());
    }

    function userList(Request $request)
    {
//        dd($request->UserInfo['id']);
        $userDto = toUserDto(Utils::copyProperties(UserDto::class, $request->all()));
        $query = BaseQuery::build(User::class);
        if (isset($userDto->id)) {
            $query->where('id', $userDto->id);
        }

//        $userlist = $query->page($userDto->pageNum)->limit($userDto->pageSize)->select();
        $userlist = Db::query("select * from tb_user user
left join  tb_wenzhang wenzhang on wenzhang.create_user_id=user.id
");
        $total = $query->count();
        return json([
            "data" => $userlist,
            "count" => $total
        ]);
    }

    function add(Request $request)
    {
        $userDto = toUserDto(Utils::copyProperties(UserDto::class, $request->all()));
        if (!isset($userDto->username)) {
            return json([
                "message" => "name不能为空",
                "code" => 500
            ]);
        }
        $id = User::save($userDto);
        return utils::ok($id);
    }

    function update(Request $request)
    {

        $userDto = toUserDto(Utils::copyProperties(UserDto::class, $request->all()));
        if (empty($userDto)) {
            return json([
                "message" => "没有修改数据"
            ]);
        }
        if (!isset($userDto->id)) {
            return json([
                "message" => "修改不能没有id"
            ]);
        }
        $query = BaseQuery::build(User::class);
        $one = $query
            ->where('id', $userDto->id)
            ->find();
        if (empty($one)) {
            return json([
                "message" => "id:{ $userDto->id }查询不到数据"
            ]);
        }
        $updateresult = User::update($userDto, [
            "id" => $userDto->id
        ]);

        return json([
            "message" => $updateresult
        ]);
    }

    function del(Request $request)
    {
        $id = $request->post("id");
        if (!isset($id)) {
            return Utils::failRes("id参数不能为空");
        }
        $userone = User::find($id);

        if (Utils::isNull($userone)) {
            return Utils::failRes("id: {$id} 找不到数据");
        }

        $result = BaseQuery::build(User::class)->where("id", $id)
            ->useSoftDelete('delete_time', Utils::dateyyyymmddhhmmss(time()))
            ->delete();
        return Utils::ok($result);
    }

    function register()
    {
        /*校验   username  password*/
        /*新增*/
    }

    function login(Request $request, RedisService $redisService)
    {
        /*校验 username password*/
        $userparams = $request->all();
        if (Utils::isNullPlus($userparams, 'username')) {
            return Utils::failRes("username 不能为空");
        }
        if (Utils::isNullPlus($userparams, 'password')) {
            return Utils::failRes("password 不能为空");
        }
        $query = BaseQuery::build(User::class);
        $result = $query->where("username", $userparams['username'])
            ->where("password", $userparams['password'])
            ->find();

        if (Utils::isNull($result, 'id')) {
            /*登录失败*/
            return Utils::failRes("账号密码不匹配", 401);
        }


        $userid = $result['id'];
        Log::info("> userid=>  $userid ");
        //region   判断是否已经存在这个用户的token
        $tokenForIds = $redisService->keys("token:$userid:*");
        $tokenForId = $tokenForIds[0] ?? '';
        Log::info("> tokenForId ==> $tokenForId");
        if (!empty($tokenForId)/*已经存在 直接返回信息*/) {
            $cacheUserResult = $redisService->get($tokenForId);
            if (Utils::isNotNull($cacheUserResult, 'id')) {
                $token = $cacheUserResult['token'] ?? '';
                if (!empty($token)) {
                    return Utils::ok([
                        "token" => $token,
                        "userInfo" => $cacheUserResult,
                    ]);
                }
            }

        }
        //endregion


        //region   存储token
        /*设置缓存*/
        $token = Md5::createTokenStr();
        Log::info("登录生token=>{$token}");


        $result['token'] = $token;

        $tokenKey = "token:$userid:$token";
        $tokenKey2 = "token:$token";
        $redisService->set($tokenKey, $result);
        $redisService->set($tokenKey2, $result);
        //endregion


        return Utils::ok("登录成功", [
            "token" => $token,
            "userInfo" => $result,
        ]);
    }

    /**
     * @desc 获取 用户的菜单
     *
     */
    function getmenu(Request $request)
    {
        /*默認選全部菜單*/
        $params = $request->all();
        if (!isset($params)) {
            return Utils::failRes("參數必填");
        }
        $query = AppFun::where('parent_id', $params['parentId'] ?? 0);
        if (Utils::isNotNull($params, 'name')) {
            $query->where("name", 'like', "%{$params['name']}");
        }
        if (Utils::isNotNull($params, 'funTypes')) {
            $query->where("fun_type", 'in', explode(',', $params['funTypes']));
        }
        if (Utils::isNotNull($params, 'id')) {
            $query->where("id", "{$params['id']}");
        }
        $result = $query->select()->toArray();
        /*加入 haveNext*/
        foreach ($result as &$item) {
            $oneExit = AppFun::where('parent_id', $item['id'])->count();
            $item['haveNext'] = $oneExit > 0;
        }
        return Utils::ok($result);
    }
}